import DocumentService from '@/services/document.service'
export const state = () => ({
  limit: 10,
  page: 1,
  options: {},
  projectId: null,
  storageCurrentPage: 1
})

export const getters = {
  offset(state) {
    return Math.floor((state.page - 1) / state.limit) * state.limit
  },
  current(state) {
    return (state.page - 1) % state.limit
  },
  page(state) {
    return state.page
  },
  limit(state) {
    return state.limit
  },
  getterStorageCurrentPage(state) {
    return state.storageCurrentPage
  }
}

export const mutations = {
  updatePage(state, page) {
    state.page = page
  },
  savePage(state) {
    const checkpoint = {}
    checkpoint[state.projectId] = state.page
    localStorage.setItem('checkpoint', JSON.stringify(checkpoint))
  },
  loadPage(state) {
    const checkpoint = JSON.parse(localStorage.getItem('checkpoint')) || {}
    state.page = checkpoint[state.projectId] ? checkpoint[state.projectId] : 1
  },
  setProjectId(state, projectId) {
    state.projectId = projectId
  },
  setOptions(state, limit, offset, q) {
    state.options = {
      limit,
      offset,
      q
    }
  },
  //  2021.8.30 添加首页加载项目取得当前项目页码并存于store中
  setProjectCurrentPage(state, currentPage) {
    const page = currentPage.completedAnnotationCount ? currentPage.completedAnnotationCount : 1
    state.storageCurrentPage = page
  },
  getProjectCurrentPage(state) {
    return state.storageCurrentPage
  }
}

export const actions = {
  prevPage({ commit, state }) {
    const page = Math.max(state.page - 1, 1)
    commit('updatePage', page)
    commit('savePage')
  },
  nextPage({ commit, state }, total) {
    const page = Math.min(state.page + 1, total)
    commit('updatePage', page)
    commit('savePage')
  },
  movePage({ commit }, newPage) {
    commit('updatePage', newPage)
    commit('savePage')
  },
  initPage({ commit }, payload) {
    commit('setProjectId', payload.projectId)
    commit('loadPage')
  },
  setOptions({ commit }, payload) {
    commit('setOptions', payload.limit, payload.offset, payload.q)
  },
  //  2021.8.30 添加首页加载项目取得当前项目页码并存于store中
  setProjectCurrentPage({ commit }, obj) {
    return DocumentService.getDefaultPage(obj.userId, obj.projectId)
      .then((response) => {
        const data = response.data ? response.data : null
        if (data !== null) {
          commit('setProjectCurrentPage', data)
        }
      })
  },
  getProjectCurrentPage({ commit }) {
    return commit('getProjectCurrentPage')
  }
}
